﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Razor.Generator;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Base;
using ZBJF.Warranty.Common.Enums.InfoCollect;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Common.Enums.SocketEnum;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.Model.ViewModel.SocketModel;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class ToBeMaintainWorkOrderController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(InsuranceWarrantyRecordModel model)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total).Include(o => o.SystemUser).Include(o => o.InsuranceOrder).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.InsuranceOrderId,
                o.WarrantyRecordNo,
                o.Reporter,
                o.ReporterPhone,
                SendBackTime = o.SendBackTime.HasValue ? o.SendBackTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                o.Status,
                StatusDesc = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetStatusName(o.Status),
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm"),
                ServiceName = o.SystemUser != null ? o.SystemUser.UserDisPlayName : string.Empty,
                SendExpressPickUpTime = o.SendExpressPickUpTime.HasValue ? o.SendExpressPickUpTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                o.InsuranceOrder.InsuranceCompany,
                o.InsuranceOrder.InsuranceCompanyBranch,
                o.InsuranceOrder.ProductName,
                o.InsuranceOrder.ProductTypeName,
                o.InsuranceOrder.SaleVendorName,
                o.InsuranceOrder.InsuranceCategoryName,
                CostTotalSecond = CommonMethod.TimeSencondToString(o.CostTotalSecond ?? (int)(DateTime.Now - o.CreateTime).TotalSeconds),
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Detail(int id)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            return View(insuranceWarrantyRecord);
        }


        #region 保存工单信息
        /// <summary>
        /// 保存工单信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="statusReasonId">状态如果有变化，可能会有状态备注</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveInsuranceWarrantyRecord(InsuranceWarrantyRecord model, int? statusReasonId)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };

            var insuranceWarrantyRecordController = new InsuranceWarrantyRecordController();

            //根据id获取工单信息
            var iwrEntity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);
            InsuranceOrder insuranceOrder = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(model.InsuranceOrderId);
            var validateInsuranceOrderMsg = new StringBuilder();
            var validateIWRMsg = new StringBuilder();
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    if (iwrEntity != null)
                    {
                        // 先记录日志
                        insuranceWarrantyRecordController.WriteOperateLog(iwrEntity, model);

                        #region 处理信息集合
                        //var insuranceWarrantyRecordItemList = model.InsuranceWarrantyRecordItem.ToList();
                        //var iwrItemsIds = new List<long>();
                        //OpreateLogs opreateLogs;
                        //foreach (var entity in insuranceWarrantyRecordItemList)
                        //{
                        //    entity.InsuranceWarrantyRecordId = model.ID;
                        //    var entity1 = entity;
                        //    var insuranceWarrantyRecordItem =
                        //        ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.LoadEntities(o => o.ID == entity1.ID).AsNoTracking().FirstOrDefault();//不修改的需要加AsNoTracking
                        //    if (insuranceWarrantyRecordItem != null)
                        //    {
                        //        iwrItemsIds.Add(entity.ID);
                        //        // 先记录日志
                        //        WriteItemOperateLog(iwrEntity.ID, entity, insuranceWarrantyRecordItem);

                        //        responseResult.Success = ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.UpdateEntities(entity);
                        //    }
                        //    else
                        //    {
                        //        if (!string.IsNullOrEmpty(entity.LostName))
                        //        {
                        //            var addedEntity =
                        //                ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.AddEntities(entity);

                        //            #region 先记录日志
                        //            opreateLogs = new OpreateLogs
                        //            {
                        //                CreatedTime = DateTime.Now,
                        //                LogTableName = "InsuranceWarrantyRecord",
                        //                LogSubject = "案件处理信息-新增",
                        //                LogTablePKID = iwrEntity.ID,
                        //                OpreateUserAccount = CurrentUser.UserAccount,
                        //                OpreateUserName = CurrentUser.UserDisPlayName
                        //            };
                        //            ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, string.Empty,
                        //                entity, OpreateType.Add);

                        //            #endregion

                        //            iwrItemsIds.Add(addedEntity.ID);
                        //            responseResult.Success = addedEntity.ID > 0;
                        //        }
                        //    }
                        //}
                        ////删除
                        //if (iwrItemsIds.Any())
                        //{
                        //    responseResult.Success = ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.DeleteBy(model.ID, iwrItemsIds, CurrentUser.UserAccount, CurrentUser.UserDisPlayName);
                        //}
                        #endregion

                        #region 其他费用处理集合
                        //var insuranceWarrantyRecordFreeList = model.InsuranceWarrantyRecordFree.ToList();
                        //var iwrFreeIds = new List<long>();
                        //foreach (var entity in insuranceWarrantyRecordFreeList)
                        //{
                        //    if (entity.FeeType <= 0 && entity.Amount <= 0)
                        //    {
                        //        continue;
                        //    }
                        //    entity.InsuranceWarrantyRecordId = model.ID;
                        //    var entity1 = entity;
                        //    var insuranceWarrantyRecordFree =
                        //        ServiceFactory.InsuranceWarrantyRecordFreeServiceInstance.LoadEntities(o => o.ID == entity1.ID).AsNoTracking().FirstOrDefault();//不修改的需要加AsNoTracking
                        //    if (insuranceWarrantyRecordFree != null)
                        //    {
                        //        iwrFreeIds.Add(entity.ID);
                        //        #region 先记录日志
                        //        opreateLogs = new OpreateLogs
                        //        {
                        //            CreatedTime = DateTime.Now,
                        //            LogTableName = "InsuranceWarrantyRecord",
                        //            LogSubject = "其他费用处理集合-修改",
                        //            LogTablePKID = iwrEntity.ID,
                        //            OpreateUserAccount = CurrentUser.UserAccount,
                        //            OpreateUserName = CurrentUser.UserDisPlayName
                        //        };
                        //        ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, new
                        //        {
                        //            insuranceWarrantyRecordFree.FeeType,
                        //            insuranceWarrantyRecordFree.Amount
                        //        }, entity);
                        //        #endregion
                        //        responseResult.Success = ServiceFactory.InsuranceWarrantyRecordFreeServiceInstance.UpdateEntities(entity);
                        //    }
                        //    else
                        //    {
                        //        var addedEntity = ServiceFactory.InsuranceWarrantyRecordFreeServiceInstance.AddEntities(entity);
                        //        #region 先记录日志
                        //        opreateLogs = new OpreateLogs
                        //        {
                        //            CreatedTime = DateTime.Now,
                        //            LogTableName = "InsuranceWarrantyRecord",
                        //            LogSubject = "其他费用处理集合-新增",
                        //            LogTablePKID = iwrEntity.ID,
                        //            OpreateUserAccount = CurrentUser.UserAccount,
                        //            OpreateUserName = CurrentUser.UserDisPlayName
                        //        };
                        //        ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, string.Empty, entity, OpreateType.Add);
                        //        #endregion
                        //        iwrFreeIds.Add(addedEntity.ID);
                        //        responseResult.Success = addedEntity.ID > 0;
                        //    }
                        //}
                        ////删除
                        //if (iwrFreeIds.Any())
                        //{
                        //    responseResult.Success = ServiceFactory.InsuranceWarrantyRecordFreeServiceInstance.DeleteBy(model.ID, iwrFreeIds, CurrentUser.UserAccount, CurrentUser.UserDisPlayName);
                        //}
                        #endregion

                        #region 关单需要信息完整
                        if (iwrEntity.Status != model.Status && model.Status == (byte)InsuranceWarrantyStatus.Close)
                        {

                            //验证保单必填数据
                            string validateIWR;
                            validateInsuranceOrderMsg.Append(insuranceWarrantyRecordController.ValidateInsuranceOrderFormData(insuranceOrder, out validateIWR));
                            validateIWRMsg.Append(validateIWR);
                            //验证保单必填数据
                            validateIWRMsg.Append(insuranceWarrantyRecordController.ValidateInsuranceWarrantyRecordFormData(iwrEntity));

                            if (!iwrEntity.CostTotalSecond.HasValue)//第一次关单，记录总耗时
                                iwrEntity.CostTotalSecond = (int)(DateTime.Now - iwrEntity.CreateTime).TotalSeconds;
                        }
                        #endregion

                        #region 报案工单状态发生改变 + 写操作流程日志
                        if (iwrEntity.Status != model.Status)
                        {
                            //获取父级状态
                            var service = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance;
                            InsuranceWarrantyRecordStatus newStatusInfo = service.LoadEntities(t => t.StatusCode == model.Status).FirstOrDefault();

                            //记录流程日志
                            InsuranceWarrantyRecordStatus oldStatusInfo = service.LoadEntities(t => t.StatusCode == iwrEntity.Status).FirstOrDefault();
                            insuranceWarrantyRecordController.WriteProcessLog(oldStatusInfo, newStatusInfo, statusReasonId, model.ID);
                        }
                        #endregion

                        //有没有数据信息不完整
                        //if (!string.IsNullOrEmpty(validateInsuranceOrderMsg.ToString()) || !string.IsNullOrEmpty(validateIWRMsg.ToString()))
                        //{
                        //    if (!string.IsNullOrEmpty(validateInsuranceOrderMsg.ToString()))
                        //    {
                        //        responseResult.Message = "保单信息不完整：" + validateInsuranceOrderMsg.ToString();
                        //    }
                        //    if (!string.IsNullOrEmpty(validateIWRMsg.ToString()))
                        //    {
                        //        responseResult.Message += "案件信息不完整：" + validateIWRMsg.ToString();
                        //    }
                        //    TempData["ResponseResult"] = responseResult;
                        //    return RedirectToAction("Detail", new { id = model.ID });
                        //}

                        #region 保存保单信息
                        if (string.IsNullOrEmpty(insuranceOrder.ThirdOrderNO))
                        {
                            insuranceOrder.ThirdOrderNO = model.InsuranceOrder.ThirdOrderNO;
                        }
                        if (!insuranceOrder.InsuranceCompanyID.HasValue)
                        {
                            insuranceOrder.InsuranceCompanyID = model.InsuranceOrder.InsuranceCompanyID;
                        }
                        if (string.IsNullOrEmpty(insuranceOrder.InsuranceCompany))
                        {
                            insuranceOrder.InsuranceCompany = model.InsuranceOrder.InsuranceCompany;
                        }
                        if (string.IsNullOrEmpty(insuranceOrder.InsuranceCompanyBranch))
                        {
                            insuranceOrder.InsuranceCompanyBranch = model.InsuranceOrder.InsuranceCompanyBranch;
                        }
                        if (!insuranceOrder.EffectiveDate.HasValue)
                        {
                            insuranceOrder.EffectiveDate = model.InsuranceOrder.EffectiveDate;
                        }
                        if (!insuranceOrder.ServiceEndTime.HasValue)
                        {
                            insuranceOrder.ServiceEndTime = model.InsuranceOrder.ServiceEndTime;
                        }
                        if (string.IsNullOrEmpty(insuranceOrder.UserName))
                        {
                            insuranceOrder.UserName = model.InsuranceOrder.UserName;
                        }
                        if (!insuranceOrder.InsuredAmount.HasValue)
                        {
                            insuranceOrder.InsuredAmount = model.InsuranceOrder.InsuredAmount;
                        }
                        if (string.IsNullOrEmpty(insuranceOrder.CertificateNO))
                        {
                            insuranceOrder.CertificateNO = model.InsuranceOrder.CertificateNO;
                        }
                        if (string.IsNullOrEmpty(insuranceOrder.IMEI))
                        {
                            insuranceOrder.IMEI = model.InsuranceOrder.IMEI;
                        }
                        if (!insuranceOrder.ProductBrandId.HasValue)
                        {
                            insuranceOrder.ProductBrandId = model.InsuranceOrder.ProductBrandId;
                            insuranceOrder.ProductBrandName = model.InsuranceOrder.ProductBrandName;
                        }
                        if (!insuranceOrder.ProductModelId.HasValue)
                        {
                            insuranceOrder.ProductModelId = model.InsuranceOrder.ProductModelId;
                            insuranceOrder.ProductModelName = model.InsuranceOrder.ProductModelName;
                        }
                        responseResult.Success = ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(insuranceOrder);
                        #endregion

                        if (responseResult.Success)
                        {
                            iwrEntity.RepairRemark = model.RepairRemark;
                            iwrEntity.Status = model.Status;
                            iwrEntity.Reporter = model.Reporter;
                            iwrEntity.InsuranceCompanyLossAdjusterName = model.InsuranceCompanyLossAdjusterName;
                            iwrEntity.ReporterPhone = model.ReporterPhone;
                            iwrEntity.LastModifyTime = DateTime.Now;
                            iwrEntity.LastModifyBy = CurrentUser.UserAccount;
                            responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(iwrEntity);
                        }
                        if (responseResult.Success)
                        {
                            ts.Complete();
                        }
                        else
                        {
                            ts.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    ts.Dispose();
                    LogHelper.WriteLog("保存报案工单信息错误：" + ex.ToString(), LogType.error);
                    responseResult.Message = "保存报案工单信息错误";
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("Detail", new { id = model.ID });
        }
        #endregion

        #region 保存远程审核维修信息
        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveRemoteAuditInsuranceWarrantyRecord(InsuranceWarrantyRecord model, InsuranceWarrantyRecordExpressInfo insuranceWarrantyRecordExpressInfo, InsuranceWarrantyRecordAccessories insuranceWarrantyRecordAccessories, IList<InsuranceWarrantyRecordAuditInfo> insuranceWarrantyRecordAuditInfo, int saveType)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Save
            };

            var warrantyRecordService = ServiceFactory.InsuranceWarrantyRecordServiceInstance;
            var auditInfoService = ServiceFactory.InsuranceWarrantyRecordAuditInfoServiceInstance;

            var insuranceWarrantyRecordController = new InsuranceWarrantyRecordController();
            var validateInsuranceOrderMsg = new StringBuilder();
            var validateIWRMsg = new StringBuilder();
            var validateIWRAuditInfoMsg = new StringBuilder();
            var validateIWRInfoCollectMsg = new StringBuilder();

            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    var entity = warrantyRecordService.LoadByID(model.ID);
                    entity.AccidentAddress = model.AccidentAddress;
                    //分拣寄修
                    if (model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.SendRevised)
                    {
                        entity.SortingCenterID = model.SortingCenterID;//必须选择分拣中心
                        entity.SortingRemark = model.SortingRemark;
                        if (saveType == 2)
                        {
                            entity.Status = (byte)InsuranceWarrantyStatus.EquipmentInSorting;
                        }
                    }
                    //到店、上门
                    else if (model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.OnsiteRepair || model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.ShopRepair)
                    {
                        entity.ServiceProviderBranchId = model.ServiceProviderBranchId;
                        if (saveType == 2)
                        {
                            entity.Status = model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.OnsiteRepair ? (byte)InsuranceWarrantyStatus.HomeMaintenance : (byte)InsuranceWarrantyStatus.HaveArrangeToStore;
                            entity.UserWarrantyRemark = model.UserWarrantyRemark;
                        }
                    }
                    else//官修
                    {
                        entity.Status = (byte)InsuranceWarrantyStatus.OfficialRepair;
                        entity.UserWarrantyRemark = model.UserWarrantyRemark;
                    }

                    entity.SortingCenterSendOrderUserID = CurrentUser.ID;//派单人
                    entity.SendOrderTime = DateTime.Now;

                    entity.LastModifyTime = DateTime.Now;
                    entity.LastModifyBy = CurrentUser.UserAccount;
                    entity.WarrantyMaintenanceTypeID = model.WarrantyMaintenanceTypeID;

                    if (model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.SendRevised && !model.SortingCenterID.HasValue)
                    {
                        responseResult.Message = "分拣寄修必须选择分拣中心！";
                    }
                    else if ((model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.OnsiteRepair || model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.ShopRepair) &&
                             !model.ServiceProviderBranchId.HasValue)
                    {
                        responseResult.Message = "上门维修或到店维修必须选择维修服务商！";
                    }
                    else
                    {
                        if (saveType == 2)
                        {
                            string validateIWR;
                            validateInsuranceOrderMsg.Append(insuranceWarrantyRecordController.ValidateInsuranceOrderFormData(entity.InsuranceOrder, out validateIWR));
                            validateIWRMsg.Append(validateIWR);
                            //验证保单必填数据
                            validateIWRMsg.Append(insuranceWarrantyRecordController.ValidateInsuranceWarrantyRecordFormData(entity));
                            if (!string.IsNullOrEmpty(validateInsuranceOrderMsg.ToString()) || !string.IsNullOrEmpty(validateIWRMsg.ToString()))
                            {
                                if (!string.IsNullOrEmpty(validateInsuranceOrderMsg.ToString()))
                                {
                                    responseResult.Message = "保单信息不完整：" + validateInsuranceOrderMsg.ToString();
                                }
                                if (!string.IsNullOrEmpty(validateIWRMsg.ToString()))
                                {
                                    responseResult.Message += "案件信息不完整：" + validateIWRMsg.ToString();
                                }
                                return Json(responseResult);
                            }
                        }
                        responseResult.Success = warrantyRecordService.UpdateEntities(entity);
                        if (responseResult.Success)
                        {
                            #region 记录状态日志
                            if (model.Status != entity.Status)
                            {
                                //获取父级状态
                                var service = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance;
                                InsuranceWarrantyRecordStatus newStatusInfo = service.LoadEntities(t => t.StatusCode == entity.Status).FirstOrDefault();

                                //记录流程日志
                                InsuranceWarrantyRecordStatus oldStatusInfo = service.LoadEntities(t => t.StatusCode == model.Status).FirstOrDefault();
                                insuranceWarrantyRecordController.WriteProcessLog(oldStatusInfo, newStatusInfo, null, model.ID);
                            }
                            #endregion

                            if (insuranceWarrantyRecordAccessories != null &&
                                insuranceWarrantyRecordAccessories.AccessoriesTypeID > 0 &&
                                insuranceWarrantyRecordAccessories.AccessoriesLevelID > 0)//保存维修配件\暂时只允许维修一个
                            {
                                insuranceWarrantyRecordAccessories.InsuranceWarrantyRecordID = model.ID;
                                var insuranceWarrantyRecordAccessoriesList =
                                    new List<InsuranceWarrantyRecordAccessories>() { insuranceWarrantyRecordAccessories };
                                responseResult.Success =
                                    ServiceFactory.InsuranceWarrantyRecordAccessoriesServiceInstance.Save(
                                        insuranceWarrantyRecordAccessoriesList, CurrentUser.UserAccount);
                            }
                            if (responseResult.Success)
                            {
                                if (insuranceWarrantyRecordAuditInfo != null && insuranceWarrantyRecordAuditInfo.Any())
                                    responseResult.Success = auditInfoService.Save(model.ID, insuranceWarrantyRecordAuditInfo,
                                        CurrentUser.UserAccount);
                                if (responseResult.Success)
                                {
                                    if (model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.SendRevised)//分拣寄修保存快递信息
                                    {
                                        var expressInfoService = ServiceFactory.InsuranceWarrantyRecordExpressInfoServiceInstance;
                                        var expressInfoEntity = expressInfoService.Load(model.ID,
                                            (byte)ExpressSendByWhoType.UserSendToPartitionCenter);
                                        if (expressInfoEntity != null)
                                        {
                                            expressInfoEntity.ExpressSendByWhoType = (byte)ExpressSendByWhoType.UserSendToPartitionCenter;
                                            expressInfoEntity.ExpressCompanyID = insuranceWarrantyRecordExpressInfo.ExpressCompanyID;
                                            expressInfoEntity.ExpressNo = insuranceWarrantyRecordExpressInfo.ExpressNo ?? "";
                                            expressInfoEntity.ExpressStatus = insuranceWarrantyRecordExpressInfo.ExpressStatus;
                                            expressInfoEntity.SendUserPhone = insuranceWarrantyRecordExpressInfo.SendUserPhone ?? "";
                                            expressInfoEntity.SendUserName = insuranceWarrantyRecordExpressInfo.SendUserName ?? "";
                                            expressInfoEntity.SendUserAddress = insuranceWarrantyRecordExpressInfo.SendUserAddress;
                                            expressInfoEntity.ExpressPrice = insuranceWarrantyRecordExpressInfo.ExpressPrice;
                                            expressInfoEntity.ReceiverUserPhone = insuranceWarrantyRecordExpressInfo.ReceiverUserPhone ?? "";
                                            expressInfoEntity.ReceiverUserName = insuranceWarrantyRecordExpressInfo.ReceiverUserName ?? "";
                                            expressInfoEntity.ReceiverUserAddress = insuranceWarrantyRecordExpressInfo.ReceiverUserAddress ?? "";
                                            expressInfoEntity.PickUpExpressManName = insuranceWarrantyRecordExpressInfo.PickUpExpressManName;
                                            expressInfoEntity.PickUpExpressManPhone = insuranceWarrantyRecordExpressInfo.PickUpExpressManPhone;
                                            responseResult.Success = expressInfoService.UpdateEntities(expressInfoEntity);
                                        }
                                        else
                                        {
                                            insuranceWarrantyRecordExpressInfo.ID = 0;
                                            insuranceWarrantyRecordExpressInfo.ExpressSendByWhoType = (byte)ExpressSendByWhoType.UserSendToPartitionCenter;
                                            insuranceWarrantyRecordExpressInfo.InsuranceWarrantyRecordID = model.ID;
                                            insuranceWarrantyRecordExpressInfo.CreatedBy = CurrentUser.UserAccount;
                                            insuranceWarrantyRecordExpressInfo.CreatedTime = DateTime.Now;
                                            responseResult.Success = expressInfoService.AddEntities(insuranceWarrantyRecordExpressInfo).ID > 0;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    ts.Dispose();
                }
            }
            return Json(responseResult);
        }
        #endregion

        public ActionResult UpdateInsuranceWarrantyRecordStatus(long status, int statusReasonId, long id, byte infoCollectWithType = 0, byte auditProjectType = 0)
        {
            var insuranceWarrantyRecordController = new InsuranceWarrantyRecordController();

            #region 报案工单状态发生改变 + 写操作流程日志
            var responseResult = new ResponseResult
            {
                OpreateType = id > 0 ? OpreateType.Update : OpreateType.Add
            };
            //根据id获取工单信息
            var iwrEntity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            var validateInsuranceOrderMsg = new StringBuilder();
            var validateIWRMsg = new StringBuilder();
            var validateIWRAuditInfoMsg = new StringBuilder();
            var validateIWRInfoCollectMsg = new StringBuilder();
            if (iwrEntity.Status != status && status > 0)
            {   //验证保单必填数据
                string validateIWR;
                validateInsuranceOrderMsg.Append(insuranceWarrantyRecordController.ValidateInsuranceOrderFormData(iwrEntity.InsuranceOrder, out validateIWR));
                validateIWRMsg.Append(validateIWR);
                //验证保单必填数据
                validateIWRMsg.Append(insuranceWarrantyRecordController.ValidateInsuranceWarrantyRecordFormData(iwrEntity));
                if (!iwrEntity.CostTotalSecond.HasValue)//第一次关单，记录总耗时
                    iwrEntity.CostTotalSecond = (int)(DateTime.Now - iwrEntity.CreateTime).TotalSeconds;
                //有没有数据错误信息
                if (!string.IsNullOrEmpty(validateInsuranceOrderMsg.ToString()) || !string.IsNullOrEmpty(validateIWRMsg.ToString()))
                {
                    if (!string.IsNullOrEmpty(validateInsuranceOrderMsg.ToString()))
                    {
                        responseResult.Message = "保单信息不完整：" + validateInsuranceOrderMsg.ToString();
                    }
                    if (!string.IsNullOrEmpty(validateIWRMsg.ToString()))
                    {
                        responseResult.Message += "案件信息不完整：" + validateIWRMsg.ToString();
                    }
                    return Json(new ResultModel(true, responseResult.Message, CodeStateEnum.Success), JsonRequestBehavior.AllowGet);
                }
                if (status == 1)
                {
                    //图片审核
                    var infoCollectItems = ServiceFactory.InsuranceProductInfoCollectItemSnapshootServiceInstance.GetInsuranceProductInfoCollectItemSnapshoot(iwrEntity.InsuranceOrderServiceProjectId??0, ServiceProductType.CellPhoneRepair, infoCollectWithType).ToList();
                    //如果快照不存在，去产品配置中取
                    if (!infoCollectItems.Any())
                    {
                        var cellPhoneInsuranceInfo = ServiceFactory.CellPhoneInsuranceInfoServiceInstance.Load(
                            iwrEntity.InsuranceOrderServiceProjectId ?? 0);
                        var cellPhoneServiceProjectID = cellPhoneInsuranceInfo != null && cellPhoneInsuranceInfo.CellPhoneServiceProjectID.HasValue
                            ? cellPhoneInsuranceInfo.CellPhoneServiceProjectID.Value
                            : 0;
                        infoCollectItems = ServiceFactory.InsuranceProductsInfoCollectItemMappingsServiceInstance.LoadInfoCollectItems(new List<int> { cellPhoneServiceProjectID }, infoCollectWithType);
                    }
                    validateIWRAuditInfoMsg.Append(ValidateInsuranceWarrantyRecordAuditInfoFormData(iwrEntity.InsuranceWarrantyRecordAuditInfo.ToList(), auditProjectType));
                    validateIWRInfoCollectMsg.Append(ValidateInsuranceWarrantyRecordInfoCollectFormData(infoCollectItems.Sum(n => n.CanUploadPicCount), iwrEntity.InsuranceWarrantyRecordInfoCollect.ToList(), infoCollectWithType));
                    if (!string.IsNullOrEmpty(validateIWRAuditInfoMsg.ToString()) ||
                        !string.IsNullOrEmpty(validateIWRInfoCollectMsg.ToString()))
                    {
                        if (!string.IsNullOrEmpty(validateIWRAuditInfoMsg.ToString()))
                        {
                            responseResult.Message += "远程分拣审核不完整：" + validateIWRAuditInfoMsg.ToString();
                        }
                        if (!string.IsNullOrEmpty(validateIWRInfoCollectMsg.ToString()))
                        {
                            responseResult.Message += "远程分拣信息不完整：" + validateIWRInfoCollectMsg.ToString();
                        }
                        return Json(new ResultModel(true, responseResult.Message, CodeStateEnum.Success),
                            JsonRequestBehavior.AllowGet);
                    }
                }
                //获取父级状态
                var service = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance;
                InsuranceWarrantyRecordStatus newStatusInfo = service.LoadEntities(t => t.StatusCode == status).FirstOrDefault();

                //记录流程日志
                InsuranceWarrantyRecordStatus oldStatusInfo = service.LoadEntities(t => t.StatusCode == iwrEntity.Status).FirstOrDefault();
                insuranceWarrantyRecordController.WriteProcessLog(oldStatusInfo, newStatusInfo, statusReasonId, id);

                iwrEntity.Status = (byte)status;
                iwrEntity.LastModifyBy = CurrentUser.UserAccount;
                iwrEntity.LastModifyTime = DateTime.Now;
                responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(iwrEntity);
            }
            #endregion
            return Json(new ResultModel(true, responseResult.Message, CodeStateEnum.Success), JsonRequestBehavior.AllowGet);
        }

        public ActionResult IWRRefuse(int insuranceWarrantyRecordId, long infoCollectWithType, long auditProjectType)
        {
            ViewBag.infoCollectWithType = infoCollectWithType;
            ViewBag.auditProjectType = auditProjectType;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordId);
            return View(list);
        }

        #region 转交工单
        [HttpPost]
        public ActionResult SaveInsuranceWarrantyRecordServiceUser(InsuranceWarrantyRecordServiceUser model)
        {
            var responseResult = new ResponseResult();
            var server = ServiceFactory.InsuranceWarrantyRecordServiceInstance;
            var warrantyRecordentity = server.LoadByID(model.InsuranceWarrantyRecordID);
            var serverServiceUser = ServiceFactory.InsuranceWarrantyRecordServiceUserServiceInstance;
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    model.CreatedBy = CurrentUser.UserAccount;
                    model.CreatedTime = DateTime.Now;
                    responseResult.Success = serverServiceUser.AddEntities(model).ID > 0;
                    if (responseResult.Success)
                    {
                        warrantyRecordentity.SystemServiceUserId = model.TakeOverOrderServiceUserID;
                        warrantyRecordentity.LastModifyBy = CurrentUser.UserAccount;
                        warrantyRecordentity.LastModifyTime = DateTime.Now;
                        responseResult.Success = server.UpdateEntities(warrantyRecordentity);
                    }
                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    responseResult.Message = e.ToString();
                    ts.Dispose();
                }
            }

            return Json(responseResult, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 验证远程分拣审核
        internal string ValidateInsuranceWarrantyRecordAuditInfoFormData(List<InsuranceWarrantyRecordAuditInfo> auditInfoList, byte auditProjectType)
        {
            var completedauditProjectConfigurationCount =
                auditInfoList.Count(n => n.AuditWith == auditProjectType);//已确定的项目
            var auditProjectConfigurationcount =
                ServiceFactory.AuditProjectConfigurationServiceInstance.LoadEntities(
                    n => n.AuditProjectWithType == auditProjectType).Count();//所有项目
            StringBuilder validateIWRMsg = new StringBuilder();
            if (completedauditProjectConfigurationCount != auditProjectConfigurationcount)
            {
                validateIWRMsg.Append("远程分拣审核不完整<br/>");
            }
            return validateIWRMsg.ToString();
        }
        #endregion

        #region 验证收集资料
        internal string ValidateInsuranceWarrantyRecordInfoCollectFormData(long canUploadPicCount, List<InsuranceWarrantyRecordInfoCollect> infoCollectEntityList, byte infoCollectWithType)
        {
            var hadUploadPicCount = infoCollectEntityList.Where(n => n.InfoCollectWith == infoCollectWithType).Sum(o => o.HadUploadPicCount);
            StringBuilder validateIWRMsg = new StringBuilder();
            if (hadUploadPicCount != canUploadPicCount)
            {
                validateIWRMsg.Append("信息图片未收集完成<br/>");
            }
            return validateIWRMsg.ToString();
        }
        #endregion
    }
}